package com.devgroupvn.guinness;

import java.io.File;
import java.util.HashMap;

import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;
import android.support.v4.util.LruCache;

import com.kin.bitmapcatching.DiskLruCache;

public class Application extends android.app.Application
{
	public static LruCache<String, Bitmap> mMemCache;
	public static DiskLruCache mDiskCache;
	private static int DISK_CACHE_SIZE = 1024 * 1024 * 10;
	private static String DISK_CACHE_SUBDIR = "cachedir";
	private static Application _instance;
	private static HashMap<Object, Object> _data = new HashMap<Object, Object>();

	@Override
	public void onCreate()
	{
		super.onCreate();
		initCaching();
	}

	public static Application getInstance()
	{
		if (null == _instance)
		{
			_instance = new Application();
		}
		return _instance;
	}

	public void putData(Object key, Object value)
	{
		_data.put(key, value);
	}

	public void removeData(Object key)
	{
		_data.remove(key);
	}

	public Object getData(Object key)
	{
		return _data.get(key);
	}

	private void initCaching()
	{
		final int memClass = ((ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE))
				.getMemoryClass();
		final int cacheSize = 1024 * 1024 * memClass /2;
		mMemCache = new LruCache<String, Bitmap>(cacheSize)
		{
			@Override
			protected int sizeOf(String key, Bitmap value)
			{
				// TODO Auto-generated method stub
				return value.getHeight() * value.getRowBytes();
			}
		};

		File cacheDir = getCacheDir(getApplicationContext(), DISK_CACHE_SUBDIR);
		if (!cacheDir.exists())
			cacheDir.mkdir();
		mDiskCache = DiskLruCache.openCache(getApplicationContext(), cacheDir, DISK_CACHE_SIZE);
	}

	public static File getCacheDir(Context context, String uniqueName)
	{
		// Check if media is mounted or storage is built-in, if so, try and use
		// external cache dir
		// otherwise use internal cache dir
		final String cachePath = Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED ? context
				.getExternalCacheDir().getPath() : context.getCacheDir().getPath();

		return new File(cachePath + File.separator + uniqueName);
	}

}
